package cn.itcast.handler;

import cn.itcast.message.ChatRequestMessage;
import cn.itcast.message.ChatResponseMessage;
import cn.itcast.server.session.Session;
import cn.itcast.server.session.SessionFactory;
import io.netty.channel.*;

@ChannelHandler.Sharable
public class ChatMessageServerHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ChatRequestMessage chatRequestMessage) throws Exception {
        Session session = SessionFactory.getSession();
        String to = chatRequestMessage.getTo();
        Channel recieveChannel = session.getChannel(to);
        ChatResponseMessage chatResponseMessage;
        if (null != recieveChannel) {
            chatResponseMessage = new ChatResponseMessage(chatRequestMessage.getFrom(), chatRequestMessage.getContent());
            recieveChannel.writeAndFlush(chatResponseMessage);
        }else{
            chatResponseMessage = new ChatResponseMessage(false, "无效目标");
            channelHandlerContext.writeAndFlush(chatResponseMessage);
        }
    }
}
